import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
// create an axios instance
const service = axios.create({
  // process.env node提供的环境变量 dev会执行.env.development
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // baseURL: '/api',
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // 判断vuex中getters有没有token
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['X-Token'] = getToken()
      config.headers['Authorization'] = 'Bearer ' + store.getters.token
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // 网络状态码 200 300
    console.log('所以正常的响应在到达浏览器之前一定会经过')
    // const res = response.data
    const { data, message, success } = response.data
    // console.log(response.data)
    if (success) {
      // 业务成功 返回响应的数据
      return data
    } else {
      // 业务失败 提示错误信息
      Message({ type: 'error', message })
      // 给浏览器返回一个错误的描述信息
      return Promise.reject(new Error(message))
    }
  },
  error => {
    console.log('所以错误的响应在到达浏览器之前一定会经过')
    // 网络状态码  401 404
    if (error.response.status === 401) {
      // 提示信息
      Message({ type: 'error', message: 'token失效' })
      // 触发action中函数  清除token和用户信息
      store.commit('user/loginout')
      // 跳转页面
      router.push('/login')
    } else {
      Message({ type: 'error', error: error.message })
    }
    // console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

export default service
